package com.jerry.spring.security.jwt.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.jerry.spring.security.jwt.constant.RedisConstant;
import com.jerry.spring.security.jwt.domain.LoginUser;
import com.jerry.spring.security.jwt.domain.vo.LoginReqVo;
import com.jerry.spring.security.jwt.domain.vo.LoginRespVo;
import com.jerry.spring.security.jwt.service.LoginService;
import com.jerry.spring.security.jwt.util.JwtUtil;
import com.jerry.spring.security.jwt.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 登录
 *
 * @author jerry 2024/5/9 14:23
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 登录
     *
     * @param vo
     * @return jwt
     */
    @Override
    public LoginRespVo login(LoginReqVo vo) {
        // 通过 AuthenticationManager 的 authenticate 方法进行认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(vo.getUsername(),
                vo.getPassword());
        // 这里 authenticate 方法会调用 UserDetailsService 的 loadUserByUsername 方法，
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        log.info("认证后的loginUser -> {}", loginUser);

        // 如果认证没有通过：给出对应提示
        if (ObjectUtil.isNull(loginUser)) {
            throw new RuntimeException("认证失败，认证信息为空");
        }

        // 如果认证通过：使用userId生成JWT，并将userId为key，用户信息为value存入Redis
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        redisUtil.setObject(RedisConstant.LOGIN_KEY + userId, loginUser);

        return new LoginRespVo(jwt);
    }

    /**
     * 注销
     */
    @Override
    public void logout() {
        // 从SecurityContextHolder中获取认证信息，解析出来userId
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)
                SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        // 删除Redis中的用户登录信息
        redisUtil.delete(RedisConstant.LOGIN_KEY + userId);
    }
}
